package com.education.platform.api.controller.article;

import com.education.platform.api.config.ThreadUser;
import com.education.platform.api.constants.RedisCacheConstant;
import com.education.platform.api.service.ArticleService;
import com.education.platform.api.service.BuyService;
import com.education.platform.api.service.RelUserPaperService;
import com.education.platform.api.service.common.CacheDataService;
import com.education.platform.api.vo.request.ArticleQueryVO;
import com.education.platform.api.vo.request.BuyArticleVO;
import com.education.platform.api.vo.response.ArticleDetailResponseVO;
import com.education.platform.api.vo.response.ArticlePageInfoVO;
import com.education.platform.api.vo.response.ArticleResponseVO;
import com.education.platform.api.vo.response.SysDictionaryResponseVO;
import com.education.platform.common.enums.ArticleTypeEnum;
import com.education.platform.common.enums.OrderTypeEnum;
import com.education.platform.common.enums.YesOrNoTypeEnum;
import com.education.platform.common.exception.BusinessException;
import com.education.platform.common.redis.RedisUtils;
import com.education.platform.common.util.BeanUtil;
import com.education.platform.common.util.StringUtils;
import com.education.platform.dao.entity.ArticleDO;
import com.education.platform.dao.model.ArticleModel;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.collections.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.ArrayList;
import java.util.List;

/**
* describe: 文章
* @author : 
* @date: 2020-07-06 09:23:16.228
**/
@RestController
@Api("文章")
@RequestMapping("article")
@Validated
public class ArticleController {
	
    private static final Logger LOGGER = LoggerFactory.getLogger(ArticleController.class);
    
	@Autowired
    private ArticleService articleService;
	@Autowired
    private RedisUtils redisUtils;
	@Autowired
    private CacheDataService cacheDataService;
	@Autowired
    private BuyService buyService;
	@Autowired
    private RelUserPaperService relUserPaperService;
    /**
     * 分页查询
     * @param articleQueryVO 分页查询参数
     * @return 分页参数
     */
    @ApiOperation(value = "分页查询文章")
    @PostMapping("getPageList")
    public ArticlePageInfoVO selectPageList(@RequestBody @Valid ArticleQueryVO articleQueryVO) {
        ArticleModel article = BeanUtil.convert(articleQueryVO, ArticleModel.class);
        article.setDeleted(false);
        article.setPublish(true);
        if(ThreadUser.getUserTokenRedisKey()!=null){
            article.setUserId(ThreadUser.getUserId());
        }
        Page<ArticleResponseVO> page = PageHelper.startPage(articleQueryVO.getPageNum(), articleQueryVO.getPageSize());
        List<ArticleModel> articleList = articleService.getArticleList(article);
        //评论数字段转换
        if(CollectionUtils.isNotEmpty(articleList)){
            articleList.parallelStream().forEach(o->{
                o.setCommentNum(o.getSelectedCommentCount());
                //评论数
                o.setCommentNum(o.getSelectedCommentCount());
                //点赞数
                String m = redisUtils.hgetStr(RedisCacheConstant.KEY_ARTICLE_LIKE, String.valueOf(o.getId()));
                if (StringUtils.isEmpty(m)) {
                    o.setLikeNum(0);
                } else {
                    o.setLikeNum(Integer.valueOf(m));
                }
            });
        }
        ArticlePageInfoVO articlePageInfo = new ArticlePageInfoVO();
        BeanUtils.copyProperties(page.toPageInfo(), articlePageInfo);
        List<ArticleResponseVO> voList = BeanUtil.convert(articleList, ArticleResponseVO.class);
        articlePageInfo.setList(voList);
        return articlePageInfo;
    }

    /**
     * 查询文章详情
     * @param
     * @return
     */
    @ApiOperation(value = "查询文章详情")
    @GetMapping("getDetailsById")
    public ArticleDetailResponseVO getDetailsById(@RequestParam Integer id) {

        ArticleDO articleDO = articleService.getById(id);
        if(articleDO == null){
            throw new BusinessException("文章不存在");
        }
        relUserPaperService.checkPermission(articleDO);
        ArticleDetailResponseVO responseVO = BeanUtil.convert(articleDO, ArticleDetailResponseVO.class);
        //获取文章点赞数
        String n = redisUtils.hgetStr(RedisCacheConstant.KEY_ARTICLE_LIKE, String.valueOf(responseVO.getId()));
        if (StringUtils.isEmpty(n)) {
            responseVO.setLikeNum(0);
        } else {
            responseVO.setLikeNum(Integer.valueOf(n));
        }
        String m = redisUtils.hgetStr(RedisCacheConstant.KEY_ARTICLE_COLLECT, String.valueOf(responseVO.getId()));
        if (StringUtils.isEmpty(m)) {
            responseVO.setCollectionNum(0);
        } else {
            responseVO.setCollectionNum(Integer.valueOf(m));
        }


        //该课程 用户是否点赞，是否收藏。
        if (StringUtils.isEmpty(ThreadUser.getUserTokenRedisKey())) {
            //未登录
            responseVO.setCollectionStatus(YesOrNoTypeEnum.N.getValue());
            responseVO.setLikeStatus(YesOrNoTypeEnum.N.getValue());

        } else {
//            已登录
            responseVO.setCollectionStatus(cacheDataService.getCollectionStatus(id,1));
            responseVO.setLikeStatus(cacheDataService.getLikeStatus(id,1));

        }
        ArticleDO articleUpdate = new ArticleDO();
        articleUpdate.setId(articleDO.getId());
        articleUpdate.setViewNumber((articleDO.getViewNumber()==null?0:articleDO.getViewNumber())+1);
        articleService.updateById(articleUpdate);

        return responseVO;
    }

    /**
     * 文章类型
     * @param
     * @return
     */
    @ApiOperation(value = "文章类型")
    @GetMapping("getArticleType")
    public List<SysDictionaryResponseVO> getArticleType() {
        List<SysDictionaryResponseVO> responseVOS = new ArrayList<>(4);
        SysDictionaryResponseVO vo;
        for(ArticleTypeEnum type:ArticleTypeEnum.values()){
            vo  = new SysDictionaryResponseVO();
            vo.setCode(type.getValue());
            vo.setName(type.getDes());
            responseVOS.add(vo);
        }
        return responseVOS;
    }

    /**
     * 购买文章
     * @param
     * @return 分页参数
     */
    @ApiOperation(value = "购买文章")
    @PostMapping("buyArticle")
    public Boolean buyArticle(@RequestBody @Valid BuyArticleVO buyArticleVO) {
        return buyService.buyProduct(OrderTypeEnum.ARTICLE_ORDER.getValue(),buyArticleVO.getId(),buyArticleVO.getTotalPrice());
    }


}
